//
//  ConnectViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/14.
//

import UIKit
import SVProgressHUD

class ConnectViewController: RViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    // 搜索loading
    @IBOutlet weak var searchView: UIView!
    
    
    
    /// 新设备
    var newDeviceList = [VTDevice]()
    var newDeviceIdList = [String]()
    /// 搜索到的历史链接设备
    var historyDeviceList = [VTDevice]()
    /// 历史链接设备id
    var historyDeviceIdList = [String]()
    /// 历史链接设备
    var historyList = [VTDevice]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.setNavigationBarHidden(true, animated: false)
//        self.searchView.isHidden = false
        self.collectionView.register(ConnectCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "ConnectCollectionReusableView")
        
        /// 本地已链接数据
        if let history = CacheManager.manager.getValueForKey(HistoryDevice) as? [VTDevice], history.count > 0 {
            self.historyDeviceList.removeAll()
            self.historyDeviceIdList.removeAll()
            self.historyList = history
            for device in history {
                self.historyDeviceIdList.append(device.identifiers)
            }
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        /// 蓝牙链接代理
        VTBLEUtils.sharedInstance().delegate = self
        VTBLEUtils.sharedInstance().startScan()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        VTBLEUtils.sharedInstance().stopScan()
    }
    
    /// 离线模式按钮
    @IBAction func offineBtnDidClicked(_ sender: UIButton) {

        /// 本地已链接数据
        if let history = CacheManager.manager.getValueForKey(HistoryDevice) as? [VTDevice], history.count > 0 {
            
            RManager.manager.currentHistoryDevice = history[CacheManager.manager.getValueForKey(OfflineDeviceIndex) as! Int]
            
        }
        self.setRootViewController()
    }
    
    /// 跳转至tabbar
    func setRootViewController() {
        
        SVProgressHUD.dismiss()
        
        let mainBundle = Bundle.main
        let main = UIStoryboard(name: "Main", bundle: mainBundle)
        let vc = main.instantiateViewController(withIdentifier: "HomeTabbarViewController") as? HomeTabbarViewController
        UIApplication.shared.keyWindow?.rootViewController = vc
    }
    
}

extension ConnectViewController: VTBLEUtilsDelegate, VTO2CommunicateDelegate {
    
    /// 蓝牙开启开始扫描
    func update(_ state: VTBLEState) {
        if state == .poweredOn {
            VTBLEUtils.sharedInstance().startScan()
        }
    }
    
    /// 发现设备
    func didDiscover(_ device: VTDevice) {
        let identifier = device.rawPeripheral.identifier.uuidString
        if newDeviceIdList.contains(identifier) {
            let index = self.newDeviceIdList.firstIndex(of: identifier) ?? NSNotFound
            newDeviceList[index] = device
            
        }else if historyDeviceIdList.contains(identifier) {
            var hadIndex = -1
            for (index, obj) in self.historyDeviceList.enumerated() {
                if obj.rawPeripheral.identifier.uuidString == identifier {
                    hadIndex = index
                    break
                }
            }
            if hadIndex == -1 {
                device.identifiers = device.rawPeripheral.identifier.uuidString
                self.historyDeviceList.append(device)
            }else {
                self.historyDeviceList[hadIndex] = device
            }
            
            // 是否自动链接设备(按app)
            if CacheManager.manager.getValueForKey(AutoConnect) as? Bool == true {
                self.connectToDeivce(device: device)
                self.collectionView.reloadData()
                return
            }
            
            // 是否自动链接设备(按设备)
//            for obj in self.historyList {
//                if obj.identifiers == identifier, obj.automicConnect == true {
//                    self.connectToDeivce(device: device)
//                    self.collectionView.reloadData()
//                    return
//                }
//            }
        }else {
            self.newDeviceList.append(device)
            self.newDeviceIdList.append(identifier)
        }
        self.collectionView.reloadData()
    }
    
    /// 链接设备
    func didConnectedDevice(_ device: VTDevice) {
        VTO2Communicate.sharedInstance().peripheral = device.rawPeripheral
        VTO2Communicate.sharedInstance().delegate = self
    }
    
    /// 设备准备成功，可以进行操作
    func serviceDeployed(_ completed: Bool) {
        if completed {
            
            /// 保存已连接设备
            /// 本地已链接数据
            if var history = CacheManager.manager.getValueForKey(HistoryDevice) as? [VTDevice], history.count > 0 {
                var have = false
                for obj in history {
                    if obj.identifiers == RManager.manager.currentDevice!.identifiers {
                        RManager.manager.currentDevice!.automicConnect = obj.automicConnect
                        have = true
                        break
                    }
                }
                if have == false {
                    RManager.manager.currentDevice!.automicConnect = true
                    history.insert(RManager.manager.currentDevice!, at: 0)
                    CacheManager.manager.setValueForKey(HistoryDevice, history as NSCoding)
                }
            }else {
                RManager.manager.currentDevice!.automicConnect = true
                CacheManager.manager.setValueForKey(HistoryDevice, [RManager.manager.currentDevice!] as NSCoding)
            }
            
            self.setRootViewController()
            
        }else {
            SVProgressHUD.dismiss()
        }
    }
    
}

extension ConnectViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return self.newDeviceList.count
        }
        return self.historyDeviceList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ConnectCollectionViewCell", for: indexPath) as! ConnectCollectionViewCell
        let device = [self.newDeviceList, self.historyDeviceList][indexPath.section][indexPath.row]
        let arr = device.advName.components(separatedBy: " ")
        cell.titleLabel.text = arr.last ?? ""
        let firstName = arr.first ?? ""
        // 小的
        if firstName.contains("s") || firstName.contains("S") {
            cell.icon.image = UIImage.init(named: "kids")
            RManager.manager.isBig = false
        }else {
            // 大的
            cell.icon.image = UIImage.init(named: "O2Ring")
            RManager.manager.isBig = true
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let device = [self.newDeviceList, self.historyDeviceList][indexPath.section][indexPath.row]
        self.connectToDeivce(device: device)
    }
    
    func connectToDeivce(device: VTDevice) {
        SVProgressHUD.show()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10) {
            SVProgressHUD.dismiss()
        }
        device.identifiers = device.rawPeripheral.identifier.uuidString
        RManager.manager.currentDevice = device
        VTBLEUtils.sharedInstance().stopScan()
        VTBLEUtils.sharedInstance().connect(to: device)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 90, height: 110)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionView.elementKindSectionHeader {
            let headView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "ConnectCollectionReusableView", for: indexPath) as! ConnectCollectionReusableView
            headView.titleLabel.text = ["新しいデバイスを追加","接続されたことのあるデバイス"][indexPath.section]
            return headView
        }
        return UICollectionReusableView.init()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: self.collectionView.width, height: 50)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 20)
    }
    
}

class ConnectCollectionReusableView: UICollectionReusableView {
    
    var titleLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.titleLabel = UILabel.init(frame: CGRect(x: 20, y: 0, width: self.width - 20, height: self.height))
        self.titleLabel.textColor = hexColor("333333")
        self.titleLabel.font = mediumFont(size: 16)
        self.addSubview(self.titleLabel)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
